package com.zhangliang.web;

import org.springframework.web.WebApplicationInitializer;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
import java.lang.reflect.Modifier;
import java.util.Iterator;
import java.util.Set;

@HandlesTypes({WebApplicationInitializer.class})
public class MySpringServletContainerInitializer implements ServletContainerInitializer {
    @Override
    public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {
        // 查找set中的WebApplicationInitializer实现类，实例化后调用对应的方法onStartup
        if (set != null) {
            Iterator<Class<?>> iterator = set.iterator();
            while (iterator.hasNext()) {
                Class<?> waiClass = iterator.next();
                if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers())
                        && WebApplicationInitializer.class.isAssignableFrom(waiClass)) {

                    try {
                        ((WebApplicationInitializer)waiClass.newInstance()).onStartup(servletContext);
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }

            }

        }
    }
}
